﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Constants;
using support = MS.InformationManagement.Support;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.DAL.Support;
using System.Data;
using System.Collections;
using System.Globalization;


namespace MS.InformationManagement.BLL.DistribucionRadicado
{
    public class DistribucionRadicado
    {

        public IEnumerable<RadicadoExterno> GetRecordDocuments(string tipo, string userName)//, int pageIndex, int pageSize, out int totalRecords)
        {
            string libraryName = MS.InformationManagement.Support.PeopleHelper.GetPropertyUserProfile(MS.InformationManagement.Support.Constants.GlobalConstants.UP_DEPARTMENT, userName);
            //int startingIndex = pageIndex * pageSize;
            SPList oList = SPContext.Current.Site.RootWeb.Lists.TryGetList(userName);
            SPList oListL = SPContext.Current.Site.RootWeb.Lists.TryGetList(libraryName);
            List<string> fields = new List<string>();
            List<string> values = new List<string>();
            List<string> types = new List<string>();
            List<string> operatorTypes = new List<string>();
            //int startingPosition = pageIndex * pageSize;

            if (!string.IsNullOrEmpty(tipo))
            {
                fields.Add(CustomSiteColumns.FIELD_DOCSET_KIND);
                values.Add(tipo);
                types.Add("Text");
                operatorTypes.Add("Eq");
            }

            fields.Add(CustomSiteColumns.FIELD_DOCSET_INTERNAL_RECEPTION);
            values.Add("1");
            types.Add("Boolean");
            operatorTypes.Add("Neq");


            string _cadena = string.Empty;
            string camlQuery = support.CamlHelper.CreateCAMLQuery(values.ToArray(), fields.ToArray(), types.ToArray(), operatorTypes.ToArray(), ref _cadena);
            List<string> viewFields = new List<string>() { CustomSiteColumns.FIELD_DOCSET_ID_RADICADO, CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE, CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT, CustomSiteColumns.FIELD_DOCUMENT_FOLIOS, CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX, "Created", CustomSiteColumns.FIELD_EXPEDIENTE_ID, CustomSiteColumns.FIELD_DOCSET_KIND, CustomSiteColumns.FIELD_DOCSET_ASUNTO, CustomSiteColumns.FIELD_DOCUMENT_NIT, CustomSiteColumns.FIELD_DOCUMENT_CEDULA, CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID };
            SPSiteDataQuery query = QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, camlQuery);
            query.Lists= "<Lists><List ID=\""+oList.ID+ "\" /><List ID=\"" +oListL.ID+ "\" /></Lists>";
            DataTable foundedItems = SPContext.Current.Web.GetSiteData(query);
            var foundedRadicados = (from item in foundedItems.Rows.OfType<DataRow>()
                                    where item[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO] != null && !string.IsNullOrEmpty(item[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO].ToString())
                                    select new RadicadoExterno
                                    {
                                        NoRadicado = item[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO].ToString(),
                                        TipoDocumento = item[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE].ToString(),
                                        RemitenteDestinatario = item[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString(),
                                        CantidadFolios = item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS] == null ? 0 : Convert.ToDouble( item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS],CultureInfo.InvariantCulture.NumberFormat),
                                        CantidadFoliosAnexos = item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX] == null ? 0 : Convert.ToDouble(item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX], CultureInfo.InvariantCulture.NumberFormat),
                                        Created = DateTime.Parse(item["Created"].ToString()),
                                        NúmeroExpediente = item[CustomSiteColumns.FIELD_EXPEDIENTE_ID] == null ? string.Empty : item[CustomSiteColumns.FIELD_EXPEDIENTE_ID].ToString(),
                                        Titulo = item[CustomSiteColumns.FIELD_DOCSET_KIND] == null ? null : new SPFieldLookupValue(item[CustomSiteColumns.FIELD_DOCSET_KIND].ToString()).LookupValue,
                                        Asunto = item[0].ToString(),//Coloque el nombre de la lista aqui item[CustomSiteColumns.FIELD_DOCSET_ASUNTO] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCSET_ASUNTO].ToString(),
                                        UsuarioAsignado = item[CustomSiteColumns.FIELD_DOCUMENT_CEDULA] == null ? item[CustomSiteColumns.FIELD_DOCUMENT_NIT] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCUMENT_NIT].ToString() : item[CustomSiteColumns.FIELD_DOCUMENT_CEDULA].ToString()
                                    });
            //totalRecords = foundedRadicados.Count();
            return foundedRadicados;//.Skip(startingPosition).Take(pageSize);
           

        }
        public void RecibirRadicado(Hashtable recibido, string userName)
        {
            try
            {
                DistributionCommand distcommand;
                Guid guid;
                foreach (DictionaryEntry item in recibido)
                {
                    guid = new Guid(item.Value.ToString());
                    distcommand = new DistributionCommand(guid, "Distribucion", item.Key.ToString(), userName);
                    distcommand.Execute();
                }
            }
            catch (Exception)
            {
                
                throw;
            }
            
        }

        //private void RecibirRadicado(Guid listRadicado, string idRadicado,string userName)
        //{
        //    SPList targetList = null;
        //    targetList = SPContext.Current.Web.Lists.GetList(listRadicado, false);
        //    SPContext.Current.Web.AllowUnsafeUpdates = true;
        //    SPQuery query = new SPQuery();
        //    query.Query = string.Concat("<Where>",
        //                                    "<Eq>",
        //                                        "<FieldRef Name='_dlc_DocId' />",
        //                                        "<Value Type='Text'>",
        //                                          idRadicado,
        //                                        "</Value>",
        //                                    "</Eq>",
        //                                "</Where>");
        //    SPListItemCollection splc = targetList.GetItems(query);

        //    if (splc.Count > 0)
        //    {
        //        SPListItem itemList = splc[0];
        //        itemList["Document_Internal_Reception"] = true;
        //        itemList.Log(itemList[CustomSiteColumns.FIELD_DOCUMENT_SUBSECCION].ToString(), DateTime.Now, support.Enums.TraceableOperation.Distribuido, userName, "Radicado Distribuido");
        //        itemList.Update();
        //    }
        //    SPContext.Current.Web.AllowUnsafeUpdates = false;
        //}

        //private void eliminarRadicadoCorrespondenciaList(string listaRecibido, string idRadicado, string userName)
        //{
        //    SPList targetList = null;
        //    targetList = SPContext.Current.Web.Lists.TryGetList(listaRecibido);
        //    SPContext.Current.Web.AllowUnsafeUpdates = true;
        //    SPQuery query = new SPQuery();
        //    query.Query = string.Concat("<Where>",
        //                                    "<Eq>",
        //                                        "<FieldRef Name='Document_Radicado' />",
        //                                        "<Value Type='Text'>",
        //                                          idRadicado,
        //                                        "</Value>",
        //                                    "</Eq>",
        //                                "</Where>");

        //    SPListItemCollection splc = targetList.GetItems(query);
        //    if (splc.Count > 0)
        //    {
        //        SPListItem itemList = splc[0];
        //        itemList.Delete();
        //        //itemList.Update();
        //    }
        //    SPContext.Current.Web.AllowUnsafeUpdates = false;
        //}
    }
}
